import { login, getUserInfo, getUserDetailById } from '@/api/user'
import { setToken, getToken, removeToken, setTimeStamp } from '@/utils/auth'
import { resetRouter } from '@/router'
export default {
  namespaced: true,
  state: () => ({
    // 先从本地取
    token: getToken() || '',
    userInfo: {}
  }),
  mutations: {
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    setUserInfo(state, userInfo) {
      state.userInfo = userInfo
    },
    // 清除用户数据的方法
    removeUserInfo(state) {
      state.token = ''
      state.userInfo = {}
      removeToken()
      // 退出登录后重置路由
      resetRouter()
    }
  },
  actions: {
    async asyncSetToken(ctx, data) {
      // console.log('登陆')
      const res = await login(data)
      ctx.commit('setToken', res)
      // 拿到token说明登陆成功 设置当前的时间戳
      setTimeStamp()
    },
    async asyncGetUserInfo(ctx) {
      const res = await getUserInfo()
      // console.log(res)
      const resDetail = await getUserDetailById(res.userId)
      // console.log(resDetail)
      ctx.commit('setUserInfo', { ...res, ...resDetail })
      // return 为了后期权限处理
      return { ...res, ...resDetail }
    },
    logout(context) {
      // 去设置权限模块下路由为初始化
      // vuex中加了命名空间的子模块之间相互调用mutations 需要在第三个参数加上{root:true}
      context.commit('permission/setRoutes', [], { root: true })
    }
  }
}
